package com.yc154.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc154.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.RequestPath;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
public class UserAuthGatewayFilterFactory extends
        AbstractGatewayFilterFactory<Object> {

    public UserAuthGatewayFilterFactory() {
        super(Object.class);
    }

    @Override
    public GatewayFilter apply(Object config) {
//        return new GatewayFilter() {
//            @Override
//            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//                return null;
//            }
//        };
        return (exchange, chain) -> {
                // 获取请求地址
                RequestPath path = exchange.getRequest().getPath();
                exchange.getResponse().getHeaders().add("Content-Type",
                    MediaType.APPLICATION_JSON_VALUE+";charset=utf-8");
                if("/auth/myinfo".equals(path.toString())) {
                    return myinfo(exchange, chain);
                } else if("/auth/logout".equals(path.toString())) {
                    return logout(exchange, chain);
                }
                // 其他的路径允许直接访问 user
                return chain.filter(exchange);
            };
    }

    // JWT 移除集合, TODO 请扩展为 redis 数据库
    Set<String> jwtRemoveSetRedis = new HashSet<>();

    private Mono<Void> logout(ServerWebExchange exchange, GatewayFilterChain chain) {
        String authorization = exchange.getRequest().getHeaders().getFirst("Authorization");
        if(authorization != null) {
            String jwt = authorization.substring("Bearer ".length());
            jwtRemoveSetRedis.add(jwt);
        }
        Map<String,Object> result = Map.of("code",1,"msg","已退出!");
        try {
            String json = new ObjectMapper().writeValueAsString(result);
            // 生成响应数据
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(json.getBytes());
            // 将数据返回浏览器
            return exchange.getResponse().writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    private Mono<Void> myinfo(ServerWebExchange exchange, GatewayFilterChain chain) {
        String authorization = exchange.getRequest().getHeaders().getFirst("Authorization");
        Map<String,Object> result;
        if(authorization == null){
            result = Map.of("code",0,"msg","未登录!");
        } else {
            String jwt = authorization.substring("Bearer ".length());
            // 如果已经退出
            if(jwtRemoveSetRedis.contains(jwt)){
                result = Map.of("code",0,"msg","未登录!");
            } else {
                try{
                    System.out.println("jwt = " + jwt);
                    Claims claims = JwtUtils.parseJWT(jwt);
                    // TODO claims 包含了用户的信息 和 jwt 功能字段, 请控制移除 jwt 功能字段
                    result = Map.of("code",1,"msg","已登录!","data", claims);
                } catch (Exception e){
                    e.printStackTrace();
                    result = Map.of("code",0,"msg","未登录!");
                }
            }
        }
        try {
            String json = new ObjectMapper().writeValueAsString(result);
            // 生成响应数据
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(json.getBytes());
            // 将数据返回浏览器
            return exchange.getResponse().writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String name() {
        return "UserAuth";
    }
}
